﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using Studio77.FunPeaceForWP7;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using Game77SharedLib;

namespace FunPeaceForWP7
{
    public partial class MainPage : PhoneApplicationPage
    {
        private static bool isShowOpenAd = false;

        Dictionary<int, Grid> pages = new Dictionary<int, Grid>();
        int currentPageIndex = 2;
        //定时处理
        int delay = 0;
        int leftSeconds = 0;
        string delayPiKey = "";
        bool isStartDelayPlay = false;
        DispatcherTimer secondTimer;
        Random r = new Random(DateTime.Now.Millisecond);

        bool usemoka = true;

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= new RoutedEventHandler(MainPage_Loaded);
            NavigationService.RemoveBackEntry();
            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(MainPage_BackKeyPress);
            this.btnPrevious.Click += new RoutedEventHandler(btnPrevious_Click);
            this.btnNext.Click += new RoutedEventHandler(btnNext_Click);

            this.sliderDelay.Maximum = 60;
            this.sliderDelay.Minimum = 0;
            this.sliderDelay.ValueChanged += new RoutedPropertyChangedEventHandler<double>(sliderDelay_ValueChanged);

            iosPageViewer1.SetCountAndCurrentIndex(3, currentPageIndex);

            pages.Add(0, ContentPanel);
            pages.Add(1, ContentPanel2);
            pages.Add(2, ContentPanel3);

            Storyboard.SetTargetName(Init.Children[0], ContentPanel.Name);
            Storyboard.SetTargetName(Init.Children[1], ContentPanel3.Name);

            Init.Begin();

            //Timer设置
            secondTimer = new DispatcherTimer();
            secondTimer.Interval = TimeSpan.FromSeconds(1);
            secondTimer.Tick += new EventHandler(secondTimer_Tick);
            secondTimer.Start();

            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            if (usemokaStr == "1" || usemokaStr == "2")
            {            
                usemoka = true;
                InitMokaBanner();
            }
            else if (usemokaStr == "0" || usemokaStr == "3")
            {
                this.mokaBanner.Visibility = System.Windows.Visibility.Collapsed;
                usemoka = false;
            }
            else
            {
                usemoka = false;
            }

            this.adView1.AdViewEvent += adView1_AdViewEvent;

            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if ((usemokaStr == "1" || usemokaStr == "3") && !isShowOpenAd)
            {
                isShowOpenAd = true;
                DispatcherTimer timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromSeconds(1);
                timer.Tick += (object ss, EventArgs ee) =>
                {
                    timer.Stop();
                    if (!string.IsNullOrEmpty(UmengSDK.UmengAnalytics.GetOnlineParam("kp_address")))
                    {
                        MokaPage.linkAddress = UmengSDK.UmengAnalytics.GetOnlineParam("kp_address");
                        MokaPage.imageAddress = UmengSDK.UmengAnalytics.GetOnlineParam("kp_img");
                    }
                    NavigationService.Navigate(new Uri("/Game77SharedLib;component/MokaPage.xaml", UriKind.RelativeOrAbsolute));
                };
                timer.Start();
            }
        }

        private void InitMokaBanner()
        {
            try
            {
                //获取间隔参数
                int intervalSec = 20;
                string secStr = UmengSDK.UmengAnalytics.GetOnlineParam("moka_banner_switch_sec");
                if (!int.TryParse(secStr, out intervalSec))
                {
                    intervalSec = 20;
                }
                int adCount = 3;
                string adCountStr = UmengSDK.UmengAnalytics.GetOnlineParam("mokaBannerCount");
                if (!int.TryParse(adCountStr, out adCount))
                {
                    adCount = 3;
                }
                List<string> imgs = new List<string>(adCount);
                List<string> address = new List<string>(adCount);
                for (int i = 1; i <= adCount; i++)
                {
                    imgs.Add(UmengSDK.UmengAnalytics.GetOnlineParam("banner" + i.ToString()));
                    address.Add(UmengSDK.UmengAnalytics.GetOnlineParam("bannerAddress" + i.ToString()));
                }
                mokaBanner.StartAd(adCount, address, imgs, intervalSec);
            }
            catch (Exception)
            {
                mokaBanner.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        void secondTimer_Tick(object sender, EventArgs e)
        {
            //timer job
            if (isStartDelayPlay)
            {
                if (leftSeconds > 0)
                {
                    leftSeconds--;
                    this.txtLeftSeconds.Text = leftSeconds.ToString();
                }
                else
                {
                    //播放
                    piMediaElement.Source = new Uri("sounds/p" + delayPiKey + ".mp3", UriKind.Relative);
                    piMediaElement.Play();
                    this.bdrDelayMask.Visibility = System.Windows.Visibility.Collapsed;
                    isStartDelayPlay = false;
                }
            }
        }

        void sliderDelay_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            //放屁延时: 0秒
            delay = Convert.ToInt32(e.NewValue);
            this.txtDelay.Text = "放屁延时: " + delay.ToString() + "秒";
        }

        void btnNext_Click(object sender, RoutedEventArgs e)
        {
            TurnNext();
        }

        private void TurnNext()
        {
            currentPageIndex++;
            if (currentPageIndex > 3)
            {
                currentPageIndex = currentPageIndex % 3;
            }
            iosPageViewer1.SetCountAndCurrentIndex(3, currentPageIndex);

            //动画
            Next.Stop();
            Storyboard.SetTargetName(Next.Children[0], pages[0].Name);
            Storyboard.SetTargetName(Next.Children[1], pages[1].Name);
            Storyboard.SetTargetName(Next.Children[2], pages[2].Name);
            Grid temp = pages[0];
            pages[0] = pages[1];
            pages[1] = pages[2];
            pages[2] = temp;
            Next.Begin();
        }

        void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            TurnPrevious();
        }

        private void TurnPrevious()
        {
            currentPageIndex--;
            if (currentPageIndex <= 0)
            {
                currentPageIndex = 3;
            }
            iosPageViewer1.SetCountAndCurrentIndex(3, currentPageIndex);

            //动画
            Prev.Stop();
            Storyboard.SetTargetName(Prev.Children[0], pages[0].Name);
            Storyboard.SetTargetName(Prev.Children[1], pages[1].Name);
            Storyboard.SetTargetName(Prev.Children[2], pages[2].Name);
            Grid temp = pages[2];
            pages[2] = pages[1];
            pages[1] = pages[0];
            pages[0] = temp;
            Prev.Begin();
        }

        void btnPi_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button != null && button.Tag != null)
            {
                string piKey = button.Tag.ToString();

                if (delay == 0)
                {
                    isStartDelayPlay = false;
                    //播放
                    piMediaElement.Source = new Uri("sounds/p" + piKey + ".mp3", UriKind.Relative);
                    piMediaElement.Play();
                }
                else
                {
                    //定时播放
                    delayPiKey = piKey;
                    leftSeconds = delay;
                    isStartDelayPlay = true;
                    this.bdrDelayMask.Visibility = System.Windows.Visibility.Visible;
                    this.txtLeftSeconds.Text = leftSeconds.ToString();
                }
            }

            ////判断是否需要出评价提示
            //if (MyAppInfos.Instance.StartCount >= 6 && !MyAppInfos.Instance.IsCommented)
            //{
            //    if (MessageBox.Show("对放屁精灵有什么意见和建议吗？去商店给个评价吧。谢谢您对开发者的支持！", "去评论吧！", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            //    {
            //        MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            //        marketplaceReviewTask.Show();
            //    }
            //    MyAppInfos.Instance.IsCommented = true;
            //}
        }

        void MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //string notice = "要退出放屁精灵吗？";
            //if (isStartDelayPlay)
            //{
            //    notice = "正在进行定时播放，确定" + notice;
            //}
            //MessageBoxResult msgRst = MessageBox.Show(notice, "提示",
            //    MessageBoxButton.OKCancel);
            //if (msgRst == MessageBoxResult.Cancel)
            //{
            //    e.Cancel = true;
            //}

            if (isStartDelayPlay)
            {
                this.bdrDelayMask.Visibility = System.Windows.Visibility.Collapsed;
                isStartDelayPlay = false;
                e.Cancel = true;
            }
        }

        private void adView1_AdViewEvent(object sender, SmartMad.Ads.WindowsPhone7.WPF.AdViewEventArgs args)
        {
            if (args.code == SmartMad.Ads.WindowsPhone7.WPF.AdViewEventCode.EVENT_NEWAD && !usemoka)
            {
                this.mokaBanner.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
        {
            if (e.Angle > 135 && e.Angle < 225)
            {
                TurnNext();
            }
            else if (e.Angle > 315 || e.Angle < 45)
            {
                TurnPrevious();
            }
        }
    }
}